/**
* @Description: 商品管理(客户)
* @author  tangbin
* @date 2023/4/11
*/

<template>
  <div class="app-containers">
    <query-table-render
        ref="queryTable"
        :query-model="queryModel"
        :table-request="requestTableData"
        :table-column="tableColumns"
        :toolbar-render="toolbarRnd"
        :transform-query="transformQuery"
        :title-render="titleRender"
        @on-operator="onOperator"
        :show-table-batch-view="showTableBatchView"
    >
      <template v-slot:form>
        <el-form-item label="渠道名称" prop="tenantId">
          <!-- :filter-method="tenantNameFilter" 
            @focus="tenantNameFocus" -->
          <el-select v-model="queryModel.tenantId" placeholder="请选择" style="width:100%" 
            clearable filterable 
            
          >
            <el-option
              v-for="item in channelInfos"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="商品编码" prop="goodsCode">
          <el-input v-model="queryModel.goodsCode" placeholder="请输入" clearable @keyup.enter.native="searchListQuery" />
        </el-form-item>
        <el-form-item label="商品名称" prop="goodsName">
          <el-input v-model="queryModel.goodsName" placeholder="请输入" clearable @keyup.enter.native="searchListQuery" />
        </el-form-item>
        <el-form-item label="数据来源" prop="source">
          <el-select v-model="queryModel.source" placeholder="请选择" style="width:100%" 
            clearable
          >
            <el-option
              v-for="item in dict.type.customer_goods_source"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="商品状态" prop="status">
          <el-select v-model="queryModel.status" placeholder="请选择" style="width:100%" clearable>
            <el-option
              v-for="item in dict.type.customer_goods_status"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>
        </el-form-item>
        
      </template>
    </query-table-render>


    <!-- 客户商品导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="600px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :on-change="fileChange"
        :auto-upload="false"
        :file-list="fileList"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>请按照模版上传文件，一次仅支持导入一个文件,仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <!-- <span v-if="this.fileMessage.length != 0" style="margin-top:10px">{{this.fileMessage}}</span> -->
      <el-table :data="fileMessage" v-if="this.fileMessage.length != 0"  style="margin-top:10px" :row-style="{height:'47px'}">
        <el-table-column label="序号" align="left" type="index" width="60"/>
        <el-table-column label="失败原因" align="left" prop="notPassed"></el-table-column>
      </el-table>
      <span v-if="this.fileMessage.length != 0" style="margin-top:10px">
        数据验证结果：共验证导入数据 <span style="color:#1890FF">{{fileMessageData.totalNum}}</span> 条，
        验证通过 <span style="color:#52C41A">{{fileMessageData.successNum}}</span> 条，
        验证失败 <span style="color:#FF4D4F">{{fileMessageData.failNum}}</span> 条</span>
      <div slot="footer" class="dialog-footer">
        <el-button @click="upload.open = false">取 消</el-button>
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 上传文件 -->
    <upload-file-dialog :title="upload.title" :uploadUrl="upload.url" 
      ref="uploadFile"
      :downloadTemplateUrl="downloadTemplateUrl" 
      :downloadTemplateName="downloadTemplateName"
      @refreshData="onRefreshTable"/>
  </div>
</template>

<script>
import {checkPermi} from '@/utils/permission.js'
import QueryTableRender from "@/components/QueryTableRender";
import UploadFileDialog from '@/components/UploadFileDialog/index.vue'
import { getToken } from "@/utils/auth";
import {customerGoodsList, customerGoodsOrgs, getTypeAndClassInfos, tenantGoodsExportById} from '@/api/basic/customerGoods.js'
import {toThousandFilter} from '@/utils/index.js'
import BigNumber from 'bignumber.js'
import {saveBlobToFile} from "@/utils/tools";

export default {
  name: "TenantCustomerManage",
  dicts: ['customer_goods_status', 'customer_goods_source', 'basic_data_goods_default_unit'], // 商品状态 数据来源 单位
  components: {QueryTableRender, UploadFileDialog},
  data() {
    return {
      queryModel: {}, // 查询参数
      tableColumns: [], // 列表
      organizeInfos: [], // 所属组织
      organizeInfosCopy: [], // 所属组织copy
      channelInfos: [], // 渠道名称
      channelInfosCopy: [], // 渠道名称
      downloadTemplateUrl: '/basic/data/tenant/goods/excelTemplateDownload', // 下载模板地址
      downloadTemplateName: '客户商品导入模板', // 下载模板文件名
      isUploadShow: false, // 是否显示上传文件弹窗
      fileList: [], // 上传使用
      // 商品导入参数
      upload: {
        // 是否显示弹出层（商品导入）
        open: false,
        // 弹出层标题（商品导入）
        title: "商品导入",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        // url: process.env.VUE_APP_BASE_API + "/basic/data/tenant/goods/goodsImport"
        url: "/basic/data/tenant/goods/goodsImport"
      },
      fileMessage:[], // 上传错误信息
      fileMessageData:{}, // 上传返回
      showTableBatchView: false, // 是否显示批量视图
    }
  },
  created() {
    this.setupQueryModel();
    this.setupTableColumns();
  },
  mounted() {
    this.getCustomerGoodsOrgs();
    // this.getTypeAndClassInfos();
  },
  watch: {
    $route(route) {
      // console.log('route=', route);
      if (route.name == 'TenantCustomerManage') {
        this.onRefreshTable();
      }
    },
    filterText(val) {
      this.$refs.menu.filter(val);
    }
  },
  methods: {
    /**
     * 初始化查询参数
     */
     setupQueryModel() {
      this.queryModel = {
        tenantId: undefined, // 渠道id名称
        goodsCode: undefined, // 商品编码
        goodsName: undefined, // 商品名称
        source: undefined, // 数据来源
        status: undefined, // 商品状态
      };
    },

    setupTableColumns() {
      this.tableColumns = [
        {
          width: '60',
          type: 'selection',
          align: 'center',
        },
        {
          label: '序号',
          width: '60',
          type: 'index',
          increment: true
        },
        {
          prop: 'goodsCode',
          label: '商品编码',
          minWidth: '180',
          showOverflowTooltip: true,
        },
        {
          prop: 'goodsName',
          label: '商品名称',
          minWidth: '260',
          showOverflowTooltip: true,
        },
        {
          prop: 'replaceCode',
          label: '替换商品编码',
          minWidth: '180',
          showOverflowTooltip: true,
        },
        {
          prop: 'source',
          label: '数据来源',
          minWidth: '180',
          align: 'left',
          showOverflowTooltip: true,
          render: (h, text) => {
            let show = "";
            this.dict.type.customer_goods_source.some((item) => {
              if (item.value === text) {
                show = item.label;
                return true;
              }
            });
            return show;
          }
        },
        {
          prop: 'defaultUnitName',
          label: '单位',
          minWidth: '100',
          align: 'left',
          render: (h, text) => {
            let show = text;
            this.dict.type.basic_data_goods_default_unit.some((item) => {
              if (item.value === text) {
                show = item.label;
                return true;
              }
            });
            return show;
          }
        },
        {
          prop: 'lastPurchasePrice',
          label: '最新进货价',
          minWidth: '140',
          align: 'right',
          render: (h, text) => {
            if (text == undefined || text == null || text == '') {
              return '';
            }
            return this.getAmountFormatter(text);
          }
        },
        {
          prop: 'averageCostPrice',
          label: '平均成本价',
          minWidth: '140',
          align: 'right',
          render: (h, text) => {
            if (text == undefined || text == null || text == '') {
              return '';
            }
            return this.getAmountFormatter(text);
          }
        },
        {
          prop: 'salesPrice',
          label: '销售价',
          minWidth: '140',
          align: 'right',
          render: (h, text) => {
            if (text == undefined || text == null || text == '') {
              return '';
            }
            return this.getAmountFormatter(text);
          }
        },
        {
          prop: 'warehouseName',
          label: '仓库',
          minWidth: '160',
          align: 'left',
          showOverflowTooltip: true,
        },
        {
          prop: 'warehouseLocationCode',
          label: '货位',
          minWidth: '150',
          align: 'left',
          showOverflowTooltip: true,
        },
        {
          prop: 'minNumber',
          label: '最小库存',
          minWidth: '100',
          align: 'right',
          showOverflowTooltip: true,
        },
        {
          prop: 'maxNumber',
          label: '最大库存',
          minWidth: '100',
          align: 'right',
          showOverflowTooltip: true,
        },
        {
          prop: 'goodsClass',
          label: '商品分类',
          minWidth: '130',
          align: 'left',
          showOverflowTooltip: true,
        },
        {
          prop: 'specsModel',
          label: '规格型号',
          minWidth: '180',
          align: 'left',
          showOverflowTooltip: true,
        },
        {
          prop: 'goodsType',
          label: '商品类型',
          minWidth: '130',
          align: 'left',
          showOverflowTooltip: true,
        },
        {
          prop: 'manufacturer',
          label: '生产厂商',
          minWidth: '130',
          align: 'left',
          showOverflowTooltip: true,
        },
        {
          prop: 'status',
          label: '状态',
          minWidth: '100',
          align: 'left',
          render: (h, text) => {
          let show = "";
          this.dict.type.customer_goods_status.some((item) => {
            if (item.value === text) {
              show = item.label;
              return true;
            }
          });
          return show;
         }
        },
        {
          prop: 'tenantName',
          label: '渠道名称',
          minWidth: '160',
          align: 'left',
          showOverflowTooltip: true,
          // render: (h, text) => {
          //   let show = "";
          //   this.belongOrgOptions.some((item) => {
          //     if (item.value === text) {
          //       show = item.label;
          //       return true;
          //     }
          //   });
          //   return show;
          // }
        },
        {
          label: '操作',
          width: '130',
          type: 'operator',
          align: "left",
          fixed: 'right',
          operators: record => { return this.operatorsFunc(record)}
        },
        
      ];
    },

    /**
     * 金额格式化
     */
     getAmountFormatter(value) {
      if (value === undefined || value === null || value === '') {
        return '';
      }
      let tm = new BigNumber(value);
      return toThousandFilter(tm.toFixed(2));
    },

    /**
     * 查询列表
     * @param {*} queryParams 
     */
    async requestTableData(queryParams) {
      return customerGoodsList(queryParams).then(res => {
        return {
          success: true,
          total: Number(res.data.total),
          data: res.data.records,
        };
      });
    },

    /**
     * 刷新列表
     */
     onRefreshTable(){
      // console.log('刷新');
      this.$refs['queryTable'].refreshTable()
    },

    toolbarRnd(h){
      let list = [];
      if (checkPermi(['basic-data:customer-goods:import'])) {
        list.push(<el-button type="primary" plain icon="el-icon-upload2" size="small" vOn:click={() => this.handleImport()}>导入</el-button>);
      }
      if (checkPermi(['basic-data:customer-goods:export'])) {
        list.push(<el-button type="primary" plain icon="el-icon-download" size="small" vOn:click={() => this.handleExport()}>导出</el-button>);
      }
      
      if (checkPermi(['basic-data:customer-goods:add'])) {
        list.push(<el-button type="primary" icon="el-icon-plus" vOn:click={() => this.handleAdd()}>新增</el-button>);
      }
      
      
      return list;
    },

    transformQuery(queryData) {
      let transParams = {}
      for (let keyName in queryData) {
        if (queryData.hasOwnProperty(keyName)) {
          transParams[keyName] = queryData[keyName]
        }
      }
      return transParams
    },

    titleRender(h) {
      return <div>
        <span style="display:inline-block; background-color: #1890FF;margin-bottom: -2px; margin-right: 8px; width: 3px; height: 14px"></span>
        <span style="display: inline-block; color: #333333; font-size: 16px;">商品列表</span>
      </div>;
    },

    /**
     * 搜索列表查询
     */
     searchListQuery() {
      this.$refs['queryTable'].submitQuery();
    },

    /**
     * 功能列表
     */
     operatorsFunc(row) {

        let list = [];
        // 数据行租户ID(渠道名称ID)与客户登录账号的租户ID，一致的时候可以修改，不一致（智科账号登录）不可以修改
        if (checkPermi(['basic-data:customer-goods:edit']) && row.tenantId == this.$store.getters.tenantId) {
          list.push({label: '修改', command: 'edit'});
        }
        
        if (checkPermi(['basic-data:customer-goods:query'])) {
          list.push({label: '详情', command: 'detail'});
        }
        return list;  
      },

    /**
     * 操作页面
     * @param {*} command 
     * @param {*} record 
     */
    onOperator(command, record) {
      // console.log('record=', record);
      let query = {
        id: record.id,
      };
      if (command == 'edit') {
        this.$router.push({path: 'TenantCustomerManageEdit', query: query});
      } else if (command == 'detail') {
        this.$router.push({path: 'TenantCustomerManageDetail', query: query});
      }
     },

     /**
     * 输入渠道名称为得到焦点调用
     * @param {*} e 
     */
     tenantNameFocus(e) {
      this.channelInfos = this.channelInfosCopy;
    },

    /**
     * 渠道名称筛选
     * @param {*} val 
     */
    tenantNameFilter(val) {
      if (val) {
        this.channelInfos = this.channelInfosCopy.filter((item) => {
          if (!!~item.name.indexOf(val)) {
            return true;
          }
        });
        if (this.channelInfos && this.channelInfos.length == 1) {
          this.$nextTick(() => {
            this.queryModel.tenantId = this.channelInfos[0].id;
          });
        } else {
          this.queryModel.tenantId = undefined;
        }
      } else {
        this.channelInfos = this.channelInfosCopy;
      }
    },

    /**
     * 输入组织名称为得到焦点调用
     * @param {*} e 
     */
    goodsOrganizeFocus(e) {
      this.organizeInfos = this.organizeInfosCopy;
    },

    /**
     * 组织名称筛选
     * @param {*} val 
     */
     goodsOrganizeFilter(val) {
      if (val) {
        this.organizeInfos = this.organizeInfosCopy.filter((item) => {
          if (!!~item.name.indexOf(val)) {
            return true;
          }
        });
        if (this.organizeInfos && this.organizeInfos.length == 1) {
          this.queryModel.goodsOrganizeId = this.organizeInfos[0].id;
        } else {
          this.queryModel.goodsOrganizeId = undefined;
        }
      } else {
        this.channelInfos = this.organizeInfosCopy;
      }
    },

    /**
     * 下载客户商品导入模板
     */
    importTemplate() {
      this.downloadFile('/basic/data/tenant/goods/excelTemplateDownload', {}, `客户商品导入模板.xlsx`);
    },

    /**
     * 商品导入改变时的钩子
     * @param {*} file 
     * @param {*} fileList 
     */
    fileChange(file, fileList) {
      this.file = file.raw;
      if (fileList.length > 0) {
        this.fileList = [fileList[fileList.length - 1]]; // 获取最后一次选择的文件
      }
    },

    /**
     * 商品导入中处理
     * @param {*} event 
     * @param {*} file 
     * @param {*} fileList 
     */
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },

    /**
     * 商品导入成功处理
     * @param {*} response 
     * @param {*} file 
     * @param {*} fileList 
     */
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.fileMessage = [];
      console.log('response===', response);
      if (response.code == 200) {
        this.fileMessageData = response.data;
        if(response.data && response.data.errorList && response.data.errorList.length != 0){
          this.$modal.msgError('导入失败')
          const errorList = response.data.errorList;
          errorList && errorList.forEach(item => {
            this.fileMessage.push({notPassed:item})
          });
        } else if (response.data && !response.data.errorList) {
          this.$modal.msgSuccess('导入成功');
          this.upload.open = false;
          this.onRefreshTable();
        }
      } else {
        this.$modal.msgError(response.msg)
      }
    },

    /**
     * 提交导入商品
     */
    submitFileForm() {
      // console.log('fileLIst=', this.fileList);
      if (this.fileList.length == 0) {
        this.$modal.msgWarning("请上传文件");
        return;
      }
      

      this.$refs.upload.submit();
    },

     /**
      * 查询所属组织和渠道下拉列表
      */
     getCustomerGoodsOrgs() {
      customerGoodsOrgs().then(res => {
        // console.log('渠道所属组织=', res);
        if (res.code == 200) {
          this.organizeInfos = (res.data.organizeInfo ? res.data.organizeInfo : []);
          this.channelInfos = (res.data.channelInfo ? res.data.channelInfo : []);
          this.organizeInfosCopy = JSON.parse(JSON.stringify(this.organizeInfos));
          this.channelInfosCopy = JSON.parse(JSON.stringify(this.channelInfos));
        }
      }).catch(err => {

      });
     },

     /**
      * 查询商品分类、商品类型下拉列表
      */
    //  getTypeAndClassInfos() {
    //   getTypeAndClassInfos().then(res => {

    //   }).catch(err => {

    //   });
    //  },

     /**
      * 新增
      */
     handleAdd() {
      this.$router.push({path: 'TenantCustomerManageAdd'});
     },

     /**
      * 导出
      */
     handleExport() {
      const selectedList = this.$refs['queryTable'].getSelection();
      let list = [];
      if (selectedList && selectedList.length > 0) {
        list = selectedList.map(item => {
          return item.id
        });
      }
      console.log('list=', list);
      if (list.length > 0) { // 根据选择的数据进行导出
        let date = this.$moment(new Date()).format("YYYY-MM-DD");
        const loading = this.$loading({
          target: this.$el,
          lock: true,
          body: true,
          text: '导出中，请稍后...',
          spinner: 'el-icon-loading',
          background: 'rgba(255, 255, 255, 0.85)'
        });

        this.$once('hook:beforeDestroy', ()=>{
          loading?.close();
        })
        tenantGoodsExportById({goodsIds: list}).then(respData => {
          saveBlobToFile(respData, `客户商品列表_${date}.xlsx`)
        }).finally(()=>{
          loading.close();
        })
        return;
      }

      // 根据查询条件进行导出
      let param = JSON.parse(JSON.stringify(this.queryModel));
      delete param.pageNum;
      delete param.pageSize;
      let date = this.$moment(new Date()).format("YYYY-MM-DD");
      this.downloadFile('/basic/data/tenant/goods/export', param, `客户商品列表_${date}.xlsx`)
     },

     /**
      * 导入
      */
     handleImport() {
      // this.fileMessageData = {};
      // this.fileMessage = [];
      // this.fileList = [];
      // this.upload.open = true;
      this.$refs.uploadFile.show();


      // this.$refs['upload'].clearFiles();
     },


  },
}
</script>


<style lang="scss" scoped>
::v-deep .el-upload-dragger{
  // margin-left: 18%!important;
  width: 558px;
}
</style>